<?php
/**
 * Notes:好友模块
 * Created by PhpStorm.
 * Author: TS
 * Date: 2019/10/9
 * Time: 9:00
 */

namespace app\index\controller;

use app\model\FriendGroup;
use app\model\FriendPush;
use app\model\Friends;
use app\model\Users;
use app\validate\FriendGroupValidate;
use app\validate\FriendPushValidate;
use app\validate\FriendValidate;

class Friend
{
    /**
     * 获取当前用户好友信息
     * @return false|string
     * @throws \think\exception\DbException
     */
    public function getFriendByUser(){
        $user_id = getNowUserId();
        $friend = new Friends();
        $users = new Users();

        $friend_list = Users::get($user_id)->friends;
        return res(1,'',$friend_list);
    }

    /**
     * 获取申请列表
     * @return false|string
     */
    public function getFriendPush(){
        if(request()->isPost()){
            $user_id = getNowUserId();
            $FriendPushMode = new FriendPush();
            $data = $FriendPushMode->getUserPush($user_id);
            return res(1,'',$data);
        }
        return res(0,MSG_NOT_POST);
    }

    /**
     * 发起好友申请
     * @return false|string
     */
    public function pushFriend(){
        if(request()->isPost()){
            $user_id = getNowUserId();      //获取当前登录用户
            $type = input('post.type');
            $FriendPushValidate = new FriendPushValidate();
            //验证类型
            if(!$FriendPushValidate->scene('type')->check(["type" => $type])) return res(0,$FriendPushValidate->getError());
            //判断发起群聊还是用户
            $type == "1" ?
                $data = request()->only('type,content,user_id,alias,group_id') :
                $data = request()->only('type,content,user_id');
            if(!$FriendPushValidate->check($data)) return  res(0,$FriendPushValidate->getError());
            //核查是否存在该用户
            if(Users::check($data['user_id']) == 0) return res(0,'无该用户');
            $friend = new Friends();
            //核查是否存在该好友
            if($friend->check($data['user_id'],$user_id) != 0 ) return res(0,'已经存在该好友');
            $data["target"] = $user_id;
            $data["status"] = 1;
            $data["push_time"] = time();
            $FriendPushModel = new FriendPush();
            $FriendPushModel->startTrans();
            $checkPush = $FriendPushModel->checkPushAndUser($data['user_id'],$user_id);
            if($checkPush){
                $updateData = [
                    'status' => 0
                ];
                if(!$FriendPushModel->edit($checkPush['friend_push_id'],$updateData)){
                    $FriendPushModel->rollback();
                    return  res(0,'添加失败');
                }

            }
            //开始添加
            if($FriendPushModel->add($data)){
                $FriendPushModel->commit();
                return res(1,MSG_SUCCESS);
            }
            return res(0,MSG_FAIL);

        }
        return res(0,MSG_NOT_POST);
    }

    /**
     * 拒绝好友申请
     * @return false|string
     */
    public function refusePush(){
        if(request()->isPost()){
            $user_id = getNowUserId();      //获取当前登录用户
            $push_id = input('post.friend_push_id');
            if(!checkNull($push_id)) return res(0,MSG_PARAM);
            $FriendPush = new FriendPush();
            //核查是否存在该申请请求
            if($FriendPush->checkWait($push_id,$user_id) == 0) return res(0,"无法处理");
//            if($FriendPush->check($push_id)) return res(0,MSG_FAIL);
            $res = $FriendPush->edit($push_id,[
                "status" => "3"
            ]);
            //开始修改数据
            if($res) return res(1,MSG_SUCCESS);
            return res(0,MSG_FAIL);

        }
        return res(0,MSG_NOT_POST);
    }

    /**
     * 同意好友申请
     * @return false|string
     * @throws \think\exception\PDOException
     */
    public function agreeFriend(){
        if (request()->isPost()){
            $uid = getNowUserId(); //获取当前登录用户
            $push_id = input('post.push_id'); //获取好友申请编号
            $FriendPush = new FriendPush();
            //核查是否存在该请求
            if($FriendPush->check($push_id) == 0) return res(0,'无该请求');
            //获取该请求
            $FriendPushModel = $FriendPush->getById($push_id);
            $status = $FriendPushModel["status"];
            //判断请求状态是否为待处理

            if($status != 1) return res(0,'请求失败，该好友申请已被' . $FriendPushModel->getStatus($status));
            //判断是否为加好友请求
            if($FriendPushModel["type"] == "1") {
                //我方数据集
                $data_my = [
                    "friend_target" => $FriendPushModel["target"],
                    "user_id" => $uid,
                    "friend_alias" => input("post.friend_alias"),
                    "friend_group" => input('post.friend_group'),
                    "add_time" => time()
                ];
                //好友方数据集
                $data_target = [
                    "friend_target" => $uid,
                    "user_id" => $FriendPushModel["target"],
                    "friend_alias" => $FriendPushModel["alias"],
                    "friend_group" => $FriendPushModel["group_id"],
                    "add_time" => time()
                ];
                //判断是否存在该用户
                if(Users::check($FriendPushModel["target"]) == 0) return res(0,'无该用户');
                //判断是否存在该分组
                if(FriendGroup::check($uid,$data_my["friend_group"]) == 0) return res(0,'无该好友分组');

                $friend = new Friends();
                //判断是否已经存在好友
                if($friend->check($uid,$data_my["friend_target"])) return res(0,'好友列表已存在该好友');
                //判断好友方是否还存在请求单中好友分组
                if(FriendGroup::check($FriendPushModel["target"],$FriendPushModel["group_id"]) == 0) {
                    //不存在，则给好友存在默认好友列表
                    $defaultGroup = FriendGroup::getDefault($FriendPushModel["target"])[0]["friend_group_id"];
                    $data_target["friend_group"] = $defaultGroup;
                }
                //开启事务
                $friend->startTrans();
                //添加当前用户方好友
                $myres = $friend->addFriend($data_my);
                if(!$myres){
                    //添加失败，数据回滚
                    $friend->rollback();
                    return res(0,'添加失败');
                }

                //添加好友方好友
                $targetres = $friend->addFriend($data_target);
                if(!$targetres){
                    //添加失败，数据回滚
                    $friend->rollback();
                    return res(0,'添加失败');
                }
                $pushModel = new FriendPush();
                //更改好友请求为已同意
                if(!$pushModel->edit($push_id,["status" => "2"])){
                    //更改失败，数据回滚
                    $friend->rollback();
                    return res(0,"添加失败");
                }
                $FriendGroupModel = new FriendGroup();
                $FriendGroupModel->startTrans();
                $my_group = $FriendGroupModel->setNumInc($data_my['friend_group']);
                if(!$my_group){
                    $FriendGroupModel->rollback();
                    $friend->rollback();
                    return  res(0,'添加失败 ');
                }
                $target_group = $FriendGroupModel->setNumInc($data_target['friend_group']);
                if(!$target_group){
                    $FriendGroupModel->rollback();
                    $friend->rollback();
                    return  res(0,'添加失败 ');
                }
                //事务提交
                $FriendGroupModel->commit();
                $friend->commit();
                return res(1,'添加成功');
            }else if ($FriendPushModel["type"] == "2"){

            }
        }
        return res(0,'请求方式错误');
    }
    public function editFriend(){
        if(request()->isPost()){
            $user_id = getNowUserId();
            $friend = input('post.friend_id');
            $friendModel = new Friends();
            if($friendModel->check($user_id,$friend) == 0) return res(0,"您还未添加该用户为好友");
            $data = request()->only('friend_alias,friend_group');
            $FriendValidate = new FriendValidate();
            if(!$FriendValidate->check($data)) return res(0,$FriendValidate->getError());
            if(FriendGroup::check($user_id,$data["friend_group"]) == 0) return res(0,'无该好友分组');
            if($friendModel->edit($user_id,$friend,$data)){
                return res(1,"修改成功");
            }
            return res(0,'修改失败');
        }
        return res(0,MSG_NOT_POST);
    }
    /**
     * 删除好友
     * @return false|string
     * @throws \think\exception\PDOException
     */
    public function delFriend(){
        if(request()->isPost()){
            $uid = getNowUserId();
            $friend_id = input('post.friend_id');  //获取好友用户ID
            $friend = new Friends();
            //验证当前用户好友列表是否存在该好友
            if ($friend->check($uid,$friend_id) == 0) return res(0,'您还未添加该用户为好友，无法删除');
            //事务开启
            $friend->startTrans();
            //从当前用户好友列表中移除
            if(!$friend->delByFriend($uid,$friend_id)){
                $friend->rollback();
                return res(0,MSG_FAIL);
            }
            //从好友方好友列表中移除
            if(!$friend->delByFriend($friend_id,$uid)){

                $friend->rollback();
                return res(0,MSG_FAIL);
            }
            $friend->commit();
            return res(1,MSG_SUCCESS);
        }
        return res(0,MSG_NOT_POST);
    }

    /**
     * 添加分组
     * @return false|string
     */
    public function addGroup(){
        //判断请求方式
        if(request()->isPost()){
            //过滤请求参数
            $data = request()->only('friend_group_name');
            if(isset($data['friend_group_name']) && $data['friend_group_name'] != ""){
                $data['user_id'] = getNowUserId(); //获取当前登录用户
                //往数据集添加数据
                $data['create_time'] = time();
                $data['num'] = 0;
                $data['online_num'] = 0;
                $data['friend_group_default'] = 0;
                //开始添加
                $friend_group = new FriendGroup();
                $res = $friend_group->addGroup($data);
                //添加成功
                if($res){
                    return res(1,MSG_SUCCESS,$res);
                }
                //添加失败
                return res(0,$friend_group->getError());
            }
            return res(0,MSG_PARAM);
        }
        return res(0,MSG_NOT_POST);
    }

    /**
     * 修改分组名
     * @return false|string
     */
    public function editGroup(){
        if(request()->isPost()){
            $group_id = input('post.friend_group_id');
            $data = request()->only('friend_group_name');
            //验证信息
            $FriendValidate = new FriendGroupValidate();
            if(!$FriendValidate->check($data)) return res(0,$FriendValidate->getError());

            $friend_group = new FriendGroup();
            //核查是否存在该分组
            if($friend_group->checkId($group_id) == 0) return res(0,MSG_PARAMFAIL);
            //开始修改
            $res = $friend_group->edit($group_id,$data);
            if($res) return res(1,MSG_SUCCESS);
            return res(0,MSG_FAIL);
        }
        return res(0,MSG_NOT_POST);
    }

    /**
     * 获取我的好友分组与分组好友
     * @return false|string
     */
    public function getGroupAndFriend(){
        if(request()->isPost()){
            $user_id = getNowUserId();
            $GroupFriendModel = new FriendGroup();
            $friend_group = $GroupFriendModel->getFriendGroup($user_id);
            $FriendsModel = new Friends();
            foreach ($friend_group as $key => $fg){
                $friend_group_id = $fg['friend_group_id'];
                $friend_group[$key]["friends"] = $FriendsModel->getGroupFriend($friend_group_id);
            }
            $res_data = $friend_group;
            return res(1,'查询成功',$res_data);
        }
        return res(0,MSG_NOT_POST);
    }

    function get_constellation($mydate,$symbol='-'){

        //计算年龄
        $birth=$mydate;
        list($by,$bm,$bd)=explode($symbol,$birth);
        $cm=date('n');
        $cd=date('j');
        $age=date('Y')-$by-1;

        if ($cm>$bm || $cm==$bm && $cd>$bd) $age++;
        $array['age'] = $age;

        //计算生肖
        $animals = array(
            '鼠', '牛', '虎', '兔', '龙', '蛇',
            '马', '羊', '猴', '鸡', '狗', '猪'
        );
        $key = ($by - 1900) % 12;
        $array['animals'] = $animals[$key];

        //计算星座
        $constellation_name = array(
            '水瓶座','双鱼座','白羊座','金牛座','双子座','巨蟹座',
            '狮子座','处女座','天秤座','天蝎座)','射手座','摩羯座'
        );
        if ($bd <= 22){
            if ('01' !== $bm) $constellation = $constellation_name[$bm-2]; else $constellation = $constellation_name[11];
        }else $constellation = $constellation_name[$bm-1];
        $array['constellation'] = $constellation;

        return $array;
    }

    /**
     *
     * @return false|string
     */
    public function getFriendById(){
        if(request()->isPost()){
            $now_user_id = getNowUserId();
            $target_id = input('post.target_id');
            $UsersModel = new Users();
            $target = $UsersModel->getUserById($target_id);
            if(!$target){
                return res(0,'好友不存在');
            }
            $FriendsModel = new Friends();
            $res_data = $target;
            $birthday = $this->get_constellation($res_data["user_birthday"]);
            $res_data["user_age"] = $birthday["age"];
            $res_data["user_animals"] = $birthday["animals"];
            $res_data["user_constellation"] = $birthday["constellation"];
            $friends = $FriendsModel->checkFriendCard($now_user_id,$target_id);
            if($friends){
                $res_data["group"] = $friends;
                $res_data['isFriend'] = 1;
                return res(1,'', $res_data);
            }
            $res_data['isFriend'] = 0;
            return res(1,'',$res_data);



        }
        return res(0,MSG_NOT_POST);
    }

    /**
     * 获取当前用户好友分组，用于好友信息编辑
     * @return false|string
     */
    public function getFriendEditGroup(){
        if(request()->isPost()){
            $user_id = getNowUserId();
            $FriendGroupModel = new FriendGroup();
            $group = $FriendGroupModel->getUserList($user_id);
            $res_data = array();
            foreach ($group as $value){
                $item = [
                    'text' => $value['friend_group_name'],
                    'value' => $value['friend_group_id']
                ];
                array_push($res_data,$item);
            }
            return res(1,'',$res_data);
        }
        return res(0,MSG_NOT_POST);
    }
    /**
     * 获取好友分组
     * @return false|string
     */
    public function getGroup(){
        if(request()->isPost()){
            $user_id = getNowUserId();
            $friend_group = new FriendGroup();
            return res(1,'',$friend_group->getUserList($user_id));
        }
        return res(0,MSG_NOT_POST);
    }

    /**
     * 删除好友分组
     * @return false|string
     */
    public function delGroup(){
        if(request()->isPost()){
            $user_id = getNowUserId();
            $group_id = input('post.friend_group_id');
            if($group_id == null) return res(0,MSG_PARAM);
            $friend_group = new FriendGroup();
            if($friend_group->checkId($group_id) == 0 ) return res(0,MSG_PARAMFAIL);

            if($friend_group->checkDefault($group_id) != 0 ) return res(0,'默认分组不可以删除');
            $friend_group->startTrans();
            if($friend_group->del($group_id)){

                $default = FriendGroup::getDefault($user_id);

                $Friend = new Friends();
                $moveDefalut = $Friend->moveDefalut($group_id,$default[0]['friend_group_id']);
                if($moveDefalut) {
                    $friend_group->commit();
                    return res(1, MSG_SUCCESS);
                }
                $friend_group->rollback();
                return res(0,MSG_FAIL);
            }
            return res(0,MSG_FAIL);
        }
        return res(0,MSG_NOT_POST);
    }

    public function getUsersByKey(){
        if (request()->isPost()){
            $key = input('post.search_key');
            $UserModel = new Users();
            $res_data = $UserModel->searchUsers($key);
            foreach ($res_data as  $index => $item){
                $birthday = get_constellation($item["user_birthday"]);
                $res_data[$index]["user_age"] = $birthday["age"];
                $res_data[$index]["user_animals"] = $birthday["animals"];
                $res_data[$index]["user_constellation"] = $birthday["constellation"];
            }

            return res(1,'',$res_data);
        }
        return res(0,MSG_NOT_POST);
    }

}